﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Axe
{
    /// <summary>
    /// 
    /// </summary>
    public class Flag
    {
        int m_ChangesCount = 0;
        bool m_FlagState;

        /// <summary>
        /// Gets the flag state changes count.
        /// </summary>
        /// <value>The changes count.</value>
        public int ChangesCount
        {
            get { return m_ChangesCount; }
        }

        #region public bool State
        public bool State
        {
            get { return m_FlagState; }
            set
            {
                bool oldState = m_FlagState;
                m_FlagState = value;

                if (oldState != m_FlagState)
                {
                    m_ChangesCount++;

                    if (m_FlagState)
                        OnFlagSet();
                    else
                        OnFlagReset();

                    OnStateChanged();
                }
            }
        } 
        #endregion


        public override int GetHashCode()
        {
            return m_FlagState.GetHashCode();
        }

        public static implicit operator bool(Flag f)
        {
            return f.State;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Flag"/> class.
        /// </summary>
        public Flag()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Flag"/> class.
        /// </summary>
        /// <param name="initialState">The initial state of the flag switch.</param>
        public Flag(bool initialState)
        {
            m_FlagState = initialState;
        }


        protected virtual void OnFlagSet()
        {
            if (FlagSet != null)
            {
                FlagSet(this, EventArgs.Empty);
            }
        }

        protected virtual void OnFlagReset()
        {
            if (FlagReset != null)
            {
                FlagReset(this, EventArgs.Empty);
            }
        }
        protected virtual void OnStateChanged()
        {
            if (StateChanged != null)
            {
                StateChanged(this, EventArgs.Empty);
            }
        }

        public event EventHandler FlagSet;
        public event EventHandler FlagReset;
        public event EventHandler StateChanged;

        public override bool Equals(object obj)
        {
            if(obj is Flag)
            {
                return ((Flag)obj).m_FlagState == this.m_FlagState;
            }

            return false;
        }
    }; 
}
